﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FitProtocolLibrary
{
    static class Fit
    {
        private static int[] crc16_table = new int[16]
        {
            0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,
            0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400
        };

        public static ushort get16crc(int crc, byte data)
        {
            int tmp;

            // compute checksum of lower four bits of byte
            tmp = crc16_table[crc & 0x0F];
            crc = (crc >> 4) & 0x0FFF;
            crc = crc ^ tmp ^ crc16_table[data & 0x0F];

            // now compute checksum of upper four bits of byte
            tmp = crc16_table[crc & 0x0F];
            crc = (crc >> 4) & 0x0FFF;
            crc = crc ^ tmp ^ crc16_table[(data >> 4) & 0x0F];

            return (ushort)crc;
        }

        public static byte[] ComputeCrc(byte[] data)
        {
            ushort crc = 0;
            foreach (byte b in data)
            {
                crc = get16crc(crc, b);
            }
            return BitConverter.GetBytes(crc);
        }
    }
}
